<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		td {
			text-align: center;
		}
	</style>
</head>
<body>
	<div id="app">
		<h1>Vue购物车</h1>
		<table border="1" style="width: 100%; border-collapse: collapse;">
			<thead>
				<tr>
					<th>选择</th>
					<th>商品</th>
					<th>单价</th>
					<th>数量</th>
					<th>小计</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="(item, index) of shoppingList">
					<td> <input type="checkbox" v-model="item.selected" @change="handleCheck"> </td>
					<td>{{ item.name }}</td>
					<td>{{ item.price }}</td>
					<td>
						<button @click="inc(index)">-</button>
						<input type="text" v-model="item.num">
						<button @click="add(index)">+</button>
					</td>
					<td>{{ (item.num * item.price).toFixed(2) }}</td>
					<td>
						<a href="javascript:void(0)" @click="del(item.id)">删除</a>
					</td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<th> <input type="checkbox" v-model="totalChecked" @change="handleTotalChecked"> 全选</th>
					<th colspan="5"> 总计：<span style="color: red; font-size: 30px;">￥{{ totalPrice }}</span> </th>
				</tr>
			</tfoot>
		</table>
	</div>
	
	<script src="vue.js"></script>
	<script>
		
		const app = new Vue({
			data() {
				return {
					shoppingList: [
						{ id: 1, name: "台灯", price: 109, num: 1, selected: false },
						{ id: 11, name: "桌子", price: 199, num: 1, selected: false },
						{ id: 2, name: "数据线", price: 19, num: 2, selected: true },
						{ id: 3, name: "垃圾桶", price: 9, num: 2, selected: false },
						{ id: 5, name: "鱼缸", price: 499, num: 1, selected: false },
					],
					totalChecked: false
				}
			},
			computed: {
				totalPrice() {
					let price = 0
					this.shoppingList.forEach((item) => {
						if (item.selected) {
							price += (item.price * item.num)
						}
					})
					return price.toFixed(2)
				}
			},
			methods: {
				del(id) {
					this.shoppingList = this.shoppingList.filter(item => item.id != id)
				},
				handleTotalChecked() {
					this.shoppingList.forEach(item => {
						item.selected = this.totalChecked
					})
				},
				handleCheck() {
					this.totalChecked = this.shoppingList.every(item => item.selected)
				},
				add(index) {
					this.shoppingList[index].num++
				},
				inc(index) {
					if (this.shoppingList[index].num > 1) {
						this.shoppingList[index].num--	
					}
				}
			},
		}).$mount("#app")
	</script>
</body>
</html>